{% extends "base.html" %}

{% block content %}
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">调试面板</h1>
</div>

<!-- 功能迁移提示 -->
<div class="alert alert-info alert-dismissible fade show" role="alert">
    <h5 class="alert-heading"><i class="bi bi-info-circle"></i> 功能迁移提示</h5>
    <p class="mb-2">
        <strong>内容生成配置</strong> 和 <strong>Prompt编辑器</strong> 功能已迁移到 <a href="/settings" class="alert-link"><i class="bi bi-gear"></i> 系统设置</a> 页面。
    </p>
    <p class="mb-0">
        在系统设置页面中，您可以：
    </p>
    <ul class="mb-0">
        <li>配置生成间隔和启用/禁用各个生成功能</li>
        <li>编辑和管理所有Prompts模板</li>
        <li>查看历史记录并使用自定义Prompts重新生成</li>
        <li>配置Debug模式和输出路径</li>
    </ul>
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>

<!-- 数据展示标签页 -->
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <ul class="nav nav-tabs card-header-tabs" id="dataTab" role="tablist">
                    <li class="nav-item" role="presentation">
                        <button class="nav-link active" id="reports-tab" data-bs-toggle="tab" data-bs-target="#reports" type="button" role="tab">
                            报告 <span id="reports-count" class="badge bg-primary">0</span>
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="todos-tab" data-bs-toggle="tab" data-bs-target="#todos" type="button" role="tab">
                            待办事项 <span id="todos-count" class="badge bg-warning">0</span>
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="activities-tab" data-bs-toggle="tab" data-bs-target="#activities" type="button" role="tab">
                            活动记录 <span id="activities-count" class="badge bg-info">0</span>
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="tips-tab" data-bs-toggle="tab" data-bs-target="#tips" type="button" role="tab">
                            提示 <span id="tips-count" class="badge bg-success">0</span>
                        </button>
                    </li>
                </ul>
            </div>
            <div class="card-body">
                <div class="tab-content" id="dataTabContent">
                    <!-- 报告标签页 -->
                    <div class="tab-pane fade show active" id="reports" role="tabpanel">
                        <div class="d-flex justify-content-between mb-3">
                            <h6>报告列表</h6>
                            <button class="btn btn-sm btn-outline-secondary" onclick="loadReports()">刷新</button>
                        </div>
                        <div id="reports-list">
                            <div class="text-center p-4">
                                <div class="spinner-border" role="status">
                                    <span class="visually-hidden">加载中...</span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 待办事项标签页 -->
                    <div class="tab-pane fade" id="todos" role="tabpanel">
                        <div class="d-flex justify-content-between mb-3">
                            <h6>待办事项列表</h6>
                            <div>
                                <select id="todo-status-filter" class="form-select form-select-sm me-2" style="width: auto; display: inline-block;">
                                    <option value="">全部</option>
                                    <option value="0">未完成</option>
                                    <option value="1">已完成</option>
                                </select>
                                <button class="btn btn-sm btn-outline-secondary" onclick="loadTodos()">刷新</button>
                            </div>
                        </div>
                        <div id="todos-list">
                            <div class="text-center p-4">
                                <div class="spinner-border" role="status">
                                    <span class="visually-hidden">加载中...</span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 活动记录标签页 -->
                    <div class="tab-pane fade" id="activities" role="tabpanel">
                        <div class="d-flex justify-content-between mb-3">
                            <h6>活动记录列表</h6>
                            <button class="btn btn-sm btn-outline-secondary" onclick="loadActivities()">刷新</button>
                        </div>
                        <div id="activities-list">
                            <div class="text-center p-4">
                                <div class="spinner-border" role="status">
                                    <span class="visually-hidden">加载中...</span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 提示标签页 -->
                    <div class="tab-pane fade" id="tips" role="tabpanel">
                        <div class="d-flex justify-content-between mb-3">
                            <h6>提示列表</h6>
                            <button class="btn btn-sm btn-outline-secondary" onclick="loadTips()">刷新</button>
                        </div>
                        <div id="tips-list">
                            <div class="text-center p-4">
                                <div class="spinner-border" role="status">
                                    <span class="visually-hidden">加载中...</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
// 页面加载时初始化
document.addEventListener('DOMContentLoaded', function() {
    loadReports();

    // 标签页切换时加载数据
    document.getElementById('todos-tab').addEventListener('shown.bs.tab', loadTodos);
    document.getElementById('activities-tab').addEventListener('shown.bs.tab', loadActivities);
    document.getElementById('tips-tab').addEventListener('shown.bs.tab', loadTips);

    // 待办状态过滤
    document.getElementById('todo-status-filter').addEventListener('change', loadTodos);
});

// 加载报告
async function loadReports() {
    try {
        const response = await fetch('/api/debug/reports?limit=20');
        const data = await response.json();

        const listEl = document.getElementById('reports-list');
        const countEl = document.getElementById('reports-count');

        if ((data.code === 0) && data.data.reports.length > 0) {
            listEl.innerHTML = data.data.reports.map(report => `
                <div class="card mb-2">
                    <div class="card-body">
                        <h6 class="card-title">${report.title}</h6>
                        <small class="text-muted">创建时间: ${new Date(report.created_at).toLocaleString()}</small>
                        <div class="mt-2">
                            <button class="btn btn-sm btn-outline-primary" onclick="showReportContent(${report.id})">查看内容</button>
                        </div>
                    </div>
                </div>
            `).join('');
            countEl.textContent = data.data.reports.length;
        } else {
            listEl.innerHTML = '<div class="text-center text-muted p-4">暂无报告数据</div>';
            countEl.textContent = '0';
        }
    } catch (error) {
        console.error('加载报告失败:', error);
        document.getElementById('reports-list').innerHTML = '<div class="text-center text-danger p-4">加载失败</div>';
    }
}

// 加载待办事项
async function loadTodos() {
    try {
        const status = document.getElementById('todo-status-filter').value;
        const url = status ? `/api/debug/todos?status=${status}&limit=20` : '/api/debug/todos?limit=20';
        const response = await fetch(url);
        const data = await response.json();

        const listEl = document.getElementById('todos-list');
        const countEl = document.getElementById('todos-count');

        if ((data.code === 0) && data.data.todos.length > 0) {
            listEl.innerHTML = data.data.todos.map(todo => `
                <div class="card mb-2">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-start">
                            <div class="flex-grow-1">
                                <p class="card-text ${todo.status === 1 ? 'text-decoration-line-through text-muted' : ''}">${todo.content}</p>
                                ${todo.reason ? `<p class="mb-1"><small class="text-secondary"><i class="bi bi-info-circle-fill"></i> 原因: ${todo.reason}</small></p>` : ''}
                                ${todo.assignee ? `<p class="mb-1"><small class="text-info"><i class="bi bi-person-fill"></i> 参与人: ${todo.assignee}</small></p>` : ''}
                                <small class="text-muted">
                                    创建: ${new Date(todo.created_at).toLocaleString()}
                                    ${todo.end_time ? ` | 截止: ${new Date(todo.end_time).toLocaleString()}` : ''}
                                </small>
                            </div>
                            <div class="ms-2">
                                <span class="badge bg-${todo.urgency === 2 ? 'danger' : todo.urgency === 1 ? 'warning' : 'secondary'} me-2">
                                    ${todo.urgency === 2 ? '高' : todo.urgency === 1 ? '中' : '低'}
                                </span>
                                <button class="btn btn-sm ${todo.status === 1 ? 'btn-outline-warning' : 'btn-outline-success'}"
                                        onclick="toggleTodoStatus(${todo.id}, ${todo.status === 1 ? 0 : 1})">
                                    ${todo.status === 1 ? '重新开启' : '完成'}
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            `).join('');
            countEl.textContent = data.data.todos.length;
        } else {
            listEl.innerHTML = '<div class="text-center text-muted p-4">暂无待办事项</div>';
            countEl.textContent = '0';
        }
    } catch (error) {
        console.error('加载待办事项失败:', error);
        document.getElementById('todos-list').innerHTML = '<div class="text-center text-danger p-4">加载失败</div>';
    }
}

// 加载活动记录
async function loadActivities() {
    try {
        const response = await fetch('/api/debug/activities?limit=20');
        const data = await response.json();

        const listEl = document.getElementById('activities-list');
        const countEl = document.getElementById('activities-count');

        if ((data.code === 0) && data.data.activities.length > 0) {
            listEl.innerHTML = data.data.activities.map(activity => {
                let resourcesHtml = '';
                if (activity.resources && activity.resources.length > 0) {
                    resourcesHtml = `
                        <div class="mt-3">
                            <h6>相关资源:</h6>
                            <div class="row">
                                ${activity.resources.map(resource => {
                                    if (resource.type === 'image') {
                                        // 处理图片路径，如果是本地路径则转换为web路径
                                        let imagePath = resource.path;
                                        if (imagePath.includes('/Users/') && imagePath.includes('/screenshots/')) {
                                            // 转换绝对路径为相对web路径
                                            const filename = imagePath.split('/').pop();
                                            imagePath = `/screenshots/${filename}`;
                                        }

                                        return `
                                            <div class="col-md-3 mb-2">
                                                <div class="card">
                                                    <img src="${imagePath}" class="card-img-top activity-image"
                                                         style="height: 100px; object-fit: cover; cursor: pointer;"
                                                         onclick="showImageModal('${imagePath}', '${resource.id}')"
                                                         onerror="handleImageError(this)">
                                                    <div class="card-body p-2">
                                                        <small class="text-muted">${resource.id}</small>
                                                    </div>
                                                </div>
                                            </div>
                                        `;
                                    } else {
                                        return `
                                            <div class="col-md-3 mb-2">
                                                <div class="card">
                                                    <div class="card-body p-2 text-center">
                                                        <i class="bi bi-file-earmark"></i>
                                                        <small class="text-muted d-block">${resource.id}</small>
                                                        <small class="text-muted">${resource.type}</small>
                                                    </div>
                                                </div>
                                            </div>
                                        `;
                                    }
                                }).join('')}
                            </div>
                        </div>
                    `;
                }

                return `
                    <div class="card mb-2">
                        <div class="card-body">
                            <h6 class="card-title">${activity.title}</h6>
                            <div class="card-text">${marked.parse(activity.content || '')}</div>
                            <small class="text-muted">
                                ${new Date(activity.start_time).toLocaleString()} - ${new Date(activity.end_time).toLocaleString()}
                            </small>
                            ${resourcesHtml}
                        </div>
                    </div>
                `;
            }).join('');
            countEl.textContent = data.data.activities.length;
        } else {
            listEl.innerHTML = '<div class="text-center text-muted p-4">暂无活动记录</div>';
            countEl.textContent = '0';
        }
    } catch (error) {
        console.error('加载活动记录失败:', error);
        document.getElementById('activities-list').innerHTML = '<div class="text-center text-danger p-4">加载失败</div>';
    }
}

// 加载提示
async function loadTips() {
    try {
        const response = await fetch('/api/debug/tips?limit=20');
        const data = await response.json();

        const listEl = document.getElementById('tips-list');
        const countEl = document.getElementById('tips-count');

        if ((data.code === 0) && data.data.tips.length > 0) {
            listEl.innerHTML = data.data.tips.map(tip => `
                <div class="card mb-2">
                    <div class="card-body">
                        <div class="card-text">${marked.parse(tip.content || '')}</div>
                        <small class="text-muted">创建时间: ${new Date(tip.created_at).toLocaleString()}</small>
                    </div>
                </div>
            `).join('');
            countEl.textContent = data.data.tips.length;
        } else {
            listEl.innerHTML = '<div class="text-center text-muted p-4">暂无提示数据</div>';
            countEl.textContent = '0';
        }
    } catch (error) {
        console.error('加载提示失败:', error);
        document.getElementById('tips-list').innerHTML = '<div class="text-center text-danger p-4">加载失败</div>';
    }
}

// 切换待办事项状态
async function toggleTodoStatus(todoId, newStatus) {
    try {
        const response = await fetch(`/api/debug/todos/${todoId}?status=${newStatus}`, { method: 'PATCH' });
        const data = await response.json();

        if (data.code === 0) {
            showAlert('状态更新成功', 'success');
            loadTodos();
        } else {
            showAlert('状态更新失败: ' + data.message, 'danger');
        }
    } catch (error) {
        showAlert('状态更新失败: ' + error.message, 'danger');
    }
}

// 显示报告内容
async function showReportContent(reportId) {
    try {
        const response = await fetch(`/api/debug/reports`);
        const data = await response.json();
        const report = data.data.reports.find(r => r.id === reportId);

        if (report) {
            // 创建模态框显示内容
            const modal = document.createElement('div');
            modal.className = 'modal fade';
            modal.innerHTML = `
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">${report.title}</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body">
                            <div>${marked.parse(report.content || '')}</div>
                        </div>
                    </div>
                </div>
            `;
            document.body.appendChild(modal);

            const bsModal = new bootstrap.Modal(modal);
            bsModal.show();

            // 模态框关闭后删除元素
            modal.addEventListener('hidden.bs.modal', () => {
                modal.remove();
            });
        }
    } catch (error) {
        showAlert('获取报告内容失败: ' + error.message, 'danger');
    }
}

// 处理图片加载错误
function handleImageError(imgElement) {
    imgElement.style.display = 'none';
    const errorDiv = document.createElement('div');
    errorDiv.className = 'text-danger p-2 text-center';
    errorDiv.innerHTML = '<small>图片加载失败</small>';
    imgElement.parentNode.appendChild(errorDiv);
}

// 显示图片模态框
function showImageModal(imagePath, imageId) {
    const modal = document.createElement('div');
    modal.className = 'modal fade';
    modal.innerHTML = `
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">资源图片: ${imageId}</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body text-center">
                    <img src="${imagePath}" class="img-fluid" style="max-width: 100%; height: auto;"
                         onerror="this.style.display='none'; this.nextElementSibling.innerHTML='<div class=&quot;text-danger p-3&quot;><i class=&quot;bi bi-exclamation-triangle&quot;></i><br>图片加载失败<br><small>${imagePath}</small></div>'">
                    <div></div>
                    <div class="mt-2">
                        <small class="text-muted">路径: ${imagePath}</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <a href="${imagePath}" target="_blank" class="btn btn-primary">在新窗口中打开</a>
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    `;
    document.body.appendChild(modal);

    const bsModal = new bootstrap.Modal(modal);
    bsModal.show();

    // 模态框关闭后删除元素
    modal.addEventListener('hidden.bs.modal', () => {
        modal.remove();
    });
}

// 显示提示消息
function showAlert(message, type = 'info') {
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
    alertDiv.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;

    // 插入到页面顶部
    const content = document.querySelector('main');
    content.insertBefore(alertDiv, content.firstChild);

    // 自动消失
    setTimeout(() => {
        if (alertDiv.parentNode) {
            alertDiv.remove();
        }
    }, 5000);
}
</script>
{% endblock %}
